<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>回调函数--重新封装缓动函数opacity与index</title>
    <style>
        #box{
            border: 1px solid #999999;
            background-color: #34fff4;
            position: absolute;
            width: 100px;
            height: 80px;
            margin: 10px auto;
            top:30px;
            left: 0;
            opacity: 0.5;
            z-index: 1;
        }
    </style>
</head>
<body>
<button>一键变换</button>
<div id="box"></div>
<script>
    //需求：点击button，div会变长变宽，然后又返回原来的值
    //知识点：回调函数  自己在形参中调用自己
    var btn=document.getElementsByTagName('button')[0];
    var box=document.getElementById('box');
    btn.onclick=function () {
        var json1={"width":400,"height":300,"left":200,"top":200,"opacity":80,"zIndex": 2};
        var json2={"width":600,"height":500,"left":400,"top":400,"opacity":30,"zIndex": 1};
        animo(box,json1,function () {
            animo(box,json2,function () {
                animo(box,json1);
            });
        });
    };

    function animo(ele,json,fn) {
        clearInterval(ele.timer);

        ele.timer=setInterval(function () {
            var bool=true;
            for (var k in json){
                var present=0;
                //获取值的方式有两种分为：opacity小数的方式；还有就是px的方式的最后需要进行px赋值
                if (k==='opacity'){
                    present=getStyle(ele,k)*100||0;
                }else{
                    present=parseInt(getStyle(ele,k))||0;
                }

                var space=(json[k]-present)/10;
                space=space>0?Math.ceil(space):Math.floor(space);
                present=present+space;

                if (k==='opacity'){
                    // present=getStyle(ele,k)*100||0;
                    ele.style[k]=present/100;//主流浏览器的赋值方式也只限于opacity
                    ele.style.filter = "alpha(opacity="+present+")";//为了兼容ie678 与上面的一段代码作用一样
                }else if (k==='zIndex'){
                    ele.style[k]=present;
                } else{
                    ele.style[k]=present+'px';//这是带有px的的赋值方式
                }

                if (json[k]!==present){
                    bool=false;
                }
            }
            console.log("看到此消息证明还么有清楚计时器");
            if(bool){
                clearInterval(ele.timer);
                if (fn){
                    fn();
                }
            }
        },10)
    }
    function getStyle(ele,zhi) {
        if (window.getComputedStyle(ele)){
            return window.getComputedStyle(ele,null)[zhi];
        }
        return  ele.currentStyle[zhi];
    }
</script>
</body>
</html>